import Vue from 'vue'
import VueRouter from 'vue-router'
import Login from '../views/Login.vue'
import jwtDecode from "jwt-decode";
Vue.use(VueRouter)

const routes = [
  {
    path: '/',
    name: 'login',
    component: Login,
  },
  {
    path: '/about',
    name: 'about',
    component: () => import('../views/AboutView.vue'),
    children: [
      {
        path: '/home',
        component: () => import('../views/index/home.vue')
      },
      {
        path: '/funds',
        component: () => import('../views/index/funds.vue')
      },
      {
        path: '/info',
        component: () => import('../views/index/info.vue')
      },
    ]
  },
  {
    path: '/register',
    component: () => import('../views/register.vue')
  },
]
 




const router = new VueRouter({
  mode: 'history',
  base: process.env.BASE_URL,
  routes
})



//前置路由守卫
router.beforeEach((to, from, next) => {
  //1.Login页面，任何时候都可以访问
  if (to.path === "/" || to.path === "/register") {
    console.log(to.path);
    next();
  } 
  //非Login页面：登录之后才能访问
  if (to.path !== "/" && to.path !== "/register") {
    let token = localStorage.getItem("token"); 
    if (!token) {
      //没有token
      next("/");
    } else {
      //有token,判断是否失效
      let { exp, name } = jwtDecode(token);
      let nowtime = new Date().getTime();
      nowtime = Math.floor(nowtime / 1000);
      if (exp - nowtime >= 0) {
        next();
      } else {
        next("/");
      }
    }
  }
});

export default router